package ru.mipt.sport.utils;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 * 
 * @author Anton Danshin <anton.danshin@frtk.ru>
 */
public class DBUtils {
    private EntityManager em;
    private EntityManagerFactory emf;

    private DBUtils() {
        init();
    }

    private void init() {
        emf = Persistence.createEntityManagerFactory("SportZPU");
        em = emf.createEntityManager();
    }

    public static DBUtils getInstance() {
        return new DBUtils();
    }

    public synchronized EntityManager getEntityManager() {
        return em;
    }

    public synchronized EntityManager getEntityManager(boolean transaction) {
        if (transaction && !em.getTransaction().isActive()) {
            em.getTransaction().begin();
        }
        return em;
    }

    public synchronized void commit() {
        if (em.isOpen()) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().commit();
            }
        }
    }
    
    public synchronized void rollback() {
        if (em.isOpen()) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
                System.out.println("DBUtils.rollback(): Transaction has been rolled back");
            } else
                System.out.println("DBUtils.rollback(): there is no active transaction");
        }
    }

    public synchronized void close() {
       if (em.isOpen()) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().commit();
            }
            em.close();
        }
        if (emf.isOpen()) {
            emf.close();
        }
    }
}
